package com.example.demo.leetcode.top100;

import java.util.LinkedList;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _46二叉树展开为链表
 * @description
 * @date 2023/06/17 11:36
 * <p>
 * ******************************************************
 */
public class _46二叉树展开为链表 {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> list = new LinkedList<>();
        transfer(root, list);
        final int size = list.size();
        TreeNode pre = root;
        TreeNode curr = null;
        list.poll();
        for (int i = 1; i < size; i++) {
            curr = list.poll();
            pre.right = curr;
            pre.left = null;
            pre = curr;
        }
    }

    private void transfer(TreeNode root, LinkedList<TreeNode> list) {
        list.add(root);
        if (root.left != null) {
            transfer(root.left, list);
        }
        if (root.right != null) {
            transfer(root.right, list);
        }
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
